﻿using MediatR;
using Newtonsoft.Json;
using S.Archives.Domain.S.ArchivesDto;
using S.Common.ApiResult;
using S.Common.Enums.Archives;
using S.EarTag.API.Mediator.MediatorCommand.AppearanceCommand;
using S.EarTag.Domain.Dto;
using S.EarTag.Domain.Model;
using S.EarTag.Infrastructure.Repository.Interface.IEarTagRepository;

namespace S.EarTag.API.Mediator.MediatorCommandHandler.AppearanceCommandHandler
{
    public class AppearanceListPageCommandHandler : IRequestHandler<AppearanceListPageCommand, ApiResult<List<AppearanceDto>>>
    {
        private readonly IAppearanceModelRepository _appearanceModelRepository;
        private readonly IConfiguration _configuration;
        public AppearanceListPageCommandHandler(IAppearanceModelRepository appearanceModelRepository, IConfiguration configuration)
        {
            _appearanceModelRepository = appearanceModelRepository;
            _configuration = configuration;
        }
        /// <summary>
        /// 查询品相测量数据+分页显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<AppearanceDto>>> Handle(AppearanceListPageCommand request, CancellationToken cancellationToken)
        {
            var list = await _appearanceModelRepository.GetAllAsync();

            var i = _configuration["eartagurl"];

            //构造HTTP请求
            HttpClient httpClient=new HttpClient();
            HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, $"{i}/ach/api/SheepFileModel/GetSheepFilesAll?id=3");
            HttpResponseMessage httpResponse=await httpClient.SendAsync(httpRequest);

            //读取响应内容
            string responseContent=await httpResponse.Content.ReadAsStringAsync();

            //反序列化响应内容为 SheepFileModel 的列表
            List<SheepFileDto> sheepFiles = JsonConvert.DeserializeObject<List<SheepFileDto>>(responseContent);

            //使用Linq进行连接查询
            var query = from a in list
                        join b in sheepFiles on a.EarTag equals b.EarTag
                        where ((string.IsNullOrEmpty(request.EarTag) || a.EarTag.Contains(request.EarTag)) &&
                        (request.VarietyEnum == 0 || b.Variety==(VarietyEnum)request.VarietyEnum) && 
                        (request.Sex==0 || b.Sex==request.Sex))
                        select new AppearanceDto
                        {
                            AppearanceId= a.AppearanceId,
                            buildingName=b.BuildingName,
                            columnName=b.ColumnName,
                            birthDate=b.BirthDate,
                            Sex=b.Sex,
                            VarietyEnum=b.Variety,
                            MeasureDate=a.MeasureDate,
                            EarTag=b.EarTag,
                            Tooth=a.Tooth,
                            Hair=a.Hair,
                            Stain=a.Stain,
                            HoofColor=a.HoofColor,
                            MouthColor=a.MouthColor,
                            Angle=a.Angle,
                            FatDistribution=a.FatDistribution,
                            CreateBy=a.CreateBy,
                            CreateDate=a.CreateDate,
                            UpdateBy=a.UpdateBy,
                            UpdateDate=a.UpdateDate,
                        };
            var list2=query.ToList();
            ApiResult<List<AppearanceDto>> apiResult = new ApiResult<List<AppearanceDto>>();
            apiResult.Data= list2;
            //总条数、总页数
            apiResult.totalCount = list2.Count();
            apiResult.pageCount = (int)Math.Ceiling((apiResult.totalCount * 1.0) / request.pageSize);
            //分页
            apiResult.Data= list2.Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
            return apiResult;
        }
    }
}
